package easyway.core.dao;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.ibatis.dao.client.DaoManager;
import com.ibatis.dao.client.template.SqlMapDaoTemplate;

import easyway.core.utils.PaginationSupport;

/**
 * BaseDAO实现类，利用ibatis模版方法实现
 * 
 *@author zhangqihang
 *@date Nor 23, 2009
 */
public abstract class AbstractBaseDAO extends SqlMapDaoTemplate implements
		BaseDAO {

	public AbstractBaseDAO(DaoManager daoManager) {
		super(daoManager);
	}

	public int deleteEntity(String sqlId, Object obj) {
		return delete(sqlId, obj);
	}

	public void insertEntity(String sqlId, Object entity) {
		insert(sqlId, entity);
	}
	//zhangqihang
	public int insertEntityResultId(String sqlId, Object entity) {
		int i=Integer.parseInt(insert(sqlId, entity).toString());
		return i;
	}
	public Object queryEntity(String sqlId, Object obj) {
		return queryForObject(sqlId, obj);
	}

	@SuppressWarnings("unchecked")
	public PaginationSupport queryForListPage(String sqlIdItem,
			String sqlTotalId, Map<String, Serializable> map) {
		List listItem = queryForList(sqlIdItem, map);
		/* 如果主键不为NULL，减少一次查询 */
		if ((map.get("pkString") != null && StringUtils.isNotEmpty(map.get(
				"pkString").toString()))
				|| (map.get("pkInteger") != null && ((Integer) map
						.get("pkInteger")).intValue() != -1)) {
			System.out.println("查询一次！");
			return new PaginationSupport(listItem, listItem.size(),
					((Integer) map.get("startResult")).intValue(),
					((Integer) map.get("pageSize")).intValue());
		}
		return new PaginationSupport(listItem, queryForTotalResult(sqlTotalId,
				map), ((Integer) map.get("startResult")).intValue(),
				((Integer) map.get("pageSize")).intValue());
	}

	@SuppressWarnings("unchecked")
	public List queryList(String sqlId, Object obj) {
		return queryForList(sqlId, obj);
	}
	
	/**
	 * @author huangww
	 */
	@SuppressWarnings("unchecked")
	public List queryList(String sqlId) {
		return queryForList(sqlId);
	}
	

	public int updateEntity(String sqlId, Object entity) {
		return update(sqlId, entity);
	}
	
	/**
	 * 查询总记录数
	 * 
	 * @param sqlTotalId 总记录数查询sql
	 * @param pa 查询的条件和分页需要的参数
	 * @return 总记录数
	 */
	@SuppressWarnings("unchecked")
	private int queryForTotalResult(String sqlTotalId, Map map) {
		return ((Integer) queryEntity(sqlTotalId, map)).intValue();
	}
	@SuppressWarnings("unchecked")  //zhangqihang 
	public int queryForSum(String sqlId, Map map) {
		Object o=queryEntity(sqlId, map);
		if(o!=null){
			return ((Integer) o).intValue();
		}else{
			return 0;
		}
		
	}
}
